package com.apchernykh.types;

import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.apchernykh.rozhlasapp.ui.RozhlasAppBaseFragmentActivity;

import android.os.Parcel;
import android.os.Parcelable;

public class RadioSchedule implements Parcelable {
	public List<RadioProgram> mPrograms = new LinkedList<RadioProgram>();
	String mUrlString;

	@Override
	public void writeToParcel(Parcel oParcel, int iUnusedFlags) {
		oParcel.writeString(mUrlString);
		oParcel.writeTypedList(mPrograms);	
	}

	public RadioSchedule(String iUrlString) {
		mUrlString = iUrlString;
	};

	public RadioSchedule(Parcel iParcel) {
		mUrlString = iParcel.readString();
		mPrograms = iParcel.createTypedArrayList(RadioProgram.CREATOR);		
	}

	public static final Parcelable.Creator<RadioSchedule> CREATOR = new Parcelable.Creator<RadioSchedule>() {
		public RadioSchedule createFromParcel(Parcel iParcel) {
			return new RadioSchedule(iParcel);
		}

		public RadioSchedule[] newArray(int iSize) {
			return new RadioSchedule[iSize];
		}
	};

	public void refresh() {
		try {
			if (mUrlString == null) {
				// Sometimes, there is no schedule, so no need for parsing.
				return;
			}
			URL url = new URL(mUrlString);
			// TODO Auto-generated method stub
			LinkedList<RadioProgram> aDecodedPrograms = new LinkedList<RadioProgram>();
			DocumentBuilderFactory aDbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder aDb;
			Document aDoc;

			try {
				aDb = aDbf.newDocumentBuilder();
				aDoc = aDb.parse(new InputSource(url.openStream()));
				aDoc.getDocumentElement().normalize();
				NodeList aNodeList = aDoc.getElementsByTagName("porad");
				for (int aNodeIter = 0; aNodeIter < aNodeList.getLength(); aNodeIter++) {
					RadioProgram aRadioProgram = new RadioProgram(aNodeList.item(aNodeIter));
					aDecodedPrograms.add(aRadioProgram);
				}
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				RozhlasAppBaseFragmentActivity.mApplicationModel.mInetInfo.signalInetFailure();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mPrograms = aDecodedPrograms;
			RozhlasAppBaseFragmentActivity.mApplicationModel.mInetInfo.signalInetRestored();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

}
